package com.demo;

import jakarta.annotation.PostConstruct;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RabbitMQProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendMessage(String message) {
        // 构建消息内容
        Message msg = new Message(message.getBytes(), new MessageProperties());
        // 发送消息到指定的交换器和路由键
        rabbitTemplate.send(RabbitMQConfig.EXCHANGE_NAME, RabbitMQConfig.ROUTING_KEY, msg);
        System.out.println("已发送消息: " + message);
    }
    @PostConstruct
    public void init() {
        // 测试发送消息
        sendMessage("Hello, RabbitMQ!");
    }
}